package Zim::Man;

use strict;
use Zim;
use File::Spec;

our $VERSION = 0.01 ;
our @ISA     = 'Zim';

my $null = File::Spec->devnull;

sub list_pages {
}

sub page_exists {
	my ($self, $page) = @_;
	$page =~ s/(^:*$self->{namespace}:*)//g;
	my $pref = $1;
	$page =~ s/:+$//;
	open MAN, "man -w $page 2> $null |";
	$_ = join '', <MAN>;
	close MAN;
	return /\S/ ? $page : ($page =~ /[A-Z]/)
		? $self->page_exists($pref.lc($page)) : undef ;
}

sub load_page {
	my ($self, $name) = @_;
	
	$name = $self->page_exists($name);
	return unless defined $name;
	
	$ENV{MANWIDTH} = 80; # FIXME get window size (via Env ?)
	open MAN, "man -c $name |" or die "Could not open pipe to man(1)\n";
	my ($block, @data);
	while (<MAN>) {
		# FIXME implement parsing algo like in Zim.pm
		# include bold and head2
		#s/((\S\cH\S)+)/<b>$1<\/b>/g;
		s/.\cH//g;
		if (/^[A-Z]+[A-Z\s]*$/) { # heading
			push @data, $block if length $block;
			push @data, [head1 => $_];
			$block = '';
		}
		elsif (/\b\w+\(\w\)/) { # links
			# FIXME namespace links per man section
			push @data, $block if length $block;
			while (s/(.*?)\b(([\w\.\-]+)\(\w+\))//) {
				push @data, $1 if length($1);
				push @data, [link => $2, $3];
			}
			$block = $_;
		}
		else { $block .= $_ }
	}
	push @data, $block if length $block;
	close MAN;
	
	my $page = Zim::Page->new($self, $self->{namespace}.':'.$name);
	$page->push_blocks(@data);
	return $page;
}

sub save_page { return } # just to be sure

1;
